<template>
	<view class="tabContent" :style="{ height: config.scrollHeight + 'px' }" style="overflow: hidden;">
		<view class="navBox">
			<up-navbar :title="titleName" style="z-index: 99;" :autoBack="true" :fixed="false" :safeAreaInsetTop="true">
			</up-navbar>

			<view style="background-color: #fff;">
				<up-tabs :current="activeTab" :list="module.treeTypes" keyName="treeTypeName" lineColor="#51d0d0"
					:inactiveStyle="{ fontSize: '14px' }" :itemStyle="{height:'44px'}"
					:activeStyle="{ fontSize: '14px',color: '#51d0d0', fontWeight: '600', transform: 'scale(1.05)' }"
					@click="scrollToSection"></up-tabs>
			</view>
		</view>

		<!-- 菜单分类明细 -->
		<scroll-view :style="{ height: scrollHeight + 'px' }" style="padding: 10px;" scroll-y scroll-with-animation
			@scroll="onScroll" :scroll-into-view="currentSection">
			<view :id="'section' + index" class="menu" v-for="(treeType, index) in module.treeTypes" :key="index">
				<view class="menu-title">
					<text>{{ treeType.treeTypeName }}</text>
				</view>
				<up-grid col="4">
					<up-grid-item v-for="(menu, pIndex) in treeType.pages" :key="pIndex" @click="checkOutMenu(menu)">
						<view class="x-c" style="padding: 10rpx;width: 40px;height: 40px;border-radius: 8px;">
							<uni-icons :fontFamily="menu.CustomFont" size="20px"
								:color="menu.AP_Colour">{{ uni.$utils.toUniCode(menu.PIC_PH) }}</uni-icons>
						</view>
						<text class="grid-text">{{ getAbbrev(menu.APFunName) }}</text>
					</up-grid-item>
				</up-grid>
			</view>
		</scroll-view>
	</view>
</template>

<script setup lang="ts" name="Menu">
	import { ref, onMounted, onUnmounted, computed, getCurrentInstance } from 'vue';
	import { onLoad, onShow } from "@dcloudio/uni-app";
	import useRequestQueue from '@/uni_modules/mc-ui/libs/http/UniversalRequestQueue';
	const { request, requestByUrl, onAllComplete, onError } = useRequestQueue();

	import { useMainStore, useInventoryStore, useUserStore, usePermissionStore } from '@/store';
	const inventoryStore = useInventoryStore();
	const mainStore = useMainStore();
	const userStore = useUserStore();
	const permissionStore = usePermissionStore();


	interface TreeType {
		treeTypeName : string;
		pages : MenuItem[];
		[key : string] : any;
	}

	interface MenuItem {
		CustomFont : string;
		AP_Colour : string;
		PIC_PH : string;
		APFunName : string;
		AP_Link : string;
		[key : string] : any;
	}

	// 类型定义
	interface Config {
		tabbarHeight : number;
		scrollHeight : number;
	}

	const { config = {
		tabbarHeight: 0,
		scrollHeight: 500
	} } = defineProps(['config'])

	// 状态
	let titleName = ref('');
	const dynamicOffset = ref(0);
	const module = ref<any>({ treeTypes: [], ModuleID: 0, ModuleName: '' });
	const activeTab = ref(0);
	const currentSection = ref('section0');
	const sectionsTop = ref<number[]>([]);
	const scrollHeight = ref(500);



	dynamicOffset.value = 44 + mainStore.systemConfig.sysDeviceInfo.statusBarHeight;
	scrollHeight.value = config.scrollHeight;
	let modules = permissionStore.appModules;

	if (!uni.$utils.isEmpty(modules)) {
		let currModuleID = inventoryStore.CurrModuleID;
		module.value = modules.find((item : any) => item.ModuleID == currModuleID);
		titleName.value = module.value.ModuleName;
	}

	// 生命周期
	onMounted(() => {

		// 延迟计算高度和位置
		setTimeout(() => {
			getScollHeightFun();
			calculateSectionTops();
		}, 200);
	});

	onUnmounted(() => {
		mainStore.appConfigInfo.routePageCurrent = 1;
	});

	// 方法
	const instance = getCurrentInstance() as any;
	const getScollHeightFun = () => {
		// uni.createSelectorQuery()
		// 	.select('.navBox')
		// 	.boundingClientRect((data : any) => {

		// 		if (data) {
		// 			scrollHeight.value = config.scrollHeight - data.height;
		// 		}
		// 	})
		// 	.exec();

		const query = uni.createSelectorQuery().in(instance.proxy);

		query.select('.navBox').boundingClientRect((data : any) => {
			if (data) {
				scrollHeight.value = config.scrollHeight - data.height;

			}
		}).exec();
		// uni.$utils.$uGetRect('.navBox').then((data : any) => {

		// })
	};

	const getAbbrev = (menuName : string) => {
		return menuName.length > 7 ? menuName.substring(0, 7) : menuName;
	};

	const scrollToSection = (item : { index : number }) => {
		activeTab.value = item.index;
		currentSection.value = `section${item.index}`;

	};

	const onScroll = (e : { detail : { scrollTop : number } }) => {
		const scrollTop = e.detail.scrollTop;
		updateActiveTab(scrollTop);
	};

	const calculateSectionTops = () => {
		const query = uni.createSelectorQuery().in(instance.proxy);

		query.selectAll('.menu').boundingClientRect((rects : any) => {
			sectionsTop.value = rects.map((rect : any) => rect.top);
		}).exec();
	};

	const updateActiveTab = (scrollTop : number) => {
		const offset = 0;
		for (let i = 0; i < sectionsTop.value.length; i++) {
			let st = 0;
			if (i === 0) {
				st = scrollTop + dynamicOffset.value + 54;
			} else {
				st = scrollTop + dynamicOffset.value + 54 + i * 10;
			}
			if (
				st + offset >= sectionsTop.value[i] &&
				(i === sectionsTop.value.length - 1 || st + offset < sectionsTop.value[i + 1])
			) {
				activeTab.value = i;
				break;
			}
		}
	};

	const checkOutMenu = (menu : MenuItem) => {
		const currModuleID = inventoryStore.CurrModuleID;
		let path = menu.AP_Link;

		inventoryStore.Menu = menu;

		// WMS模块特殊处理
		if (currModuleID === 4 && path.indexOf('hybrid') > -1) {
			path = '/st_wms/BoxCode/list';
		} else if (currModuleID == 1 && path.indexOf('/commonPage/kanban') > -1) {
			uni.navigateTo({
				url: path
			})
			return;
			// uni.$utils.layer.alert("暂未开通此功能！")
		} else if (currModuleID == 1 && path.indexOf('/commonPage/Report') > -1) {
			// 跳转报表
			// path = mainStore.appConfigInfo.IPAgreement + mainStore.appConfigInfo.serverIP + '/ReportList/APPTable?moduleName=' + menu.Para + '&win_size=win_medium';
			let port = mainStore.appConfigInfo.serverIP.split(':')[1];

			path = mainStore.appConfigInfo.ICPServerIP + '/AppTable.html?moduleName=' + menu.Para + '&port=' + port + '&win_size=win_medium';


			uni.$utils.navigateToWebView({
				url: path,
				title: menu.APFunName,
				navBgColor: '#51d0d0',
				navTextColor: '#ffffff'
			});
			return;
		}



		uni.navigateTo({
			url: path,
		});
	};

	const CloseShopPage = () => {
		uni.navigateBack({
			delta: 999,
		});
	};
</script>

<style lang="scss" scoped>
	$h-padding: 5px;
	$v-padding: 10px;
	$radius: 5px;

	scroll-view {
		box-sizing: border-box;
	}

	.sv {
		padding: $v-padding $h-padding;
		height: calc(100vh - (50px + env(safe-area-inset-bottom)) - (44px + 44px + env(safe-area-inset-top)) - 20px);
	}

	.tabContent {
		display: flex;
		flex-direction: column;
		background-color: #f2f1f6;

		.menu {
			padding: $v-padding $h-padding;
			margin-bottom: $v-padding;
			background-color: #ffffff;
			border-radius: $radius;

			&-title {
				padding-left: 10px;
				display: flex;
				justify-content: flex-start;
				align-items: center;
				width: 100%;
				height: 35px;
				font-size: 14px;
				font-weight: 500;
			}
		}
	}

	.grid-text {
		font-size: 12px;
		color: #909399;
		padding: 5px 0 10px 0;
		/* #ifndef APP-PLUS */
		box-sizing: border-box;
		/* #endif */
	}
</style>